import JsRsaSign from "jsrsasign";
export function signBySHA256WithRSA(privateKey, msg) {
	return new Promise((reslove,reject)=>{
		const key = JsRsaSign.KEYUTIL.getKey(privateKey);
		const signature = new JsRsaSign.KJUR.crypto.Signature({
			alg: "SHA256withRSA",
			});
			signature.init(key);
			signature.updateString(msg);
			let a = JsRsaSign.hextob64(signature.sign())
			reslove(a)
	})
}

export function havSign(uri){
	let startIndex = uri.indexOf('/association-api');
	let result = uri.substring(startIndex);
	if (result.includes('?')) {
	  result = result.split('?')[0];
	} else {
	  result = result;
	}
	return new Promise((resolve,reject)=>{
	  let timestamp = Date.now() + ''
	  let nonce = wxuuid()
	  let str = {"timestamp":timestamp,"nonce":nonce,"uri":result}
	  let sign = ''
	  signBySHA256WithRSA(privateKey,JSON.stringify(str)).then(res=>{
		sign = res
		let obj = {
		  timestamp,nonce,sign
		}
		resolve(obj)
	  })
	})
  }
export const privateKey = `
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOMwnEN5aB9dU4lWTkkhwv+U4JkqV3Da73mEM7C7BQApo4yXFGV71ebgP0EkfK5Cb2Hanu5YJ7StWbyJYCEVp+Y9mx2CamkAhADfpkz5PT1MDEyiBjEIfvIvvVwwhKnXmTShRxO8HJcG5s+kRVFbDqOCHvOY7KrywL4qbEi5dLOFAgMBAAECgYAfJpkmf00Rj+BWYmkVifWMycMJ/U5EASD4znGv99S1sv/j1QtM5u/rWjASJIib9CwFhM5p69h145b8TPHLV4bPvtSNUQ3kONSANz7Rq6Qs64xnYVUM4Y4Cn7mWAJEF8M1eCuwdL++e6lS0C9uWIQlzIRw1OQrgvnBMnm0m48IAwQJBAPiC1oKODbWquPmuO2Re0YjXFpou7R7X+ntdDIfljNwVpzyFQWnmbbxlFKm3X4LmiiAMWSb85ZX2YfwTdOCjvkkCQQDqCUm+3zniC+dxTno8cbEcrov10t83WBsJx4/sy17L5n+KL9ePx//eqL/OSxxGXPg0y181tWAE2CztDqmLL/tdAkBlfpo5a+bxgS5W2u/qyEbviljy06OIa1EjvRb3Eat732QT9aCHrdK3lNjhj8D0Z0+WUzS+FZ92pc/S8edUL8vxAkEAuOUdne49jJhbAOk/KQGpKz+60zsFnnO86L0At9Lz0aMIn+OsKauYOhCXeCNe8zf/37XMQmJIuYsP8zjiOVRvAQJBAMednneBuCdhyqoebSax6Dp2JmKkB+0LFFEJdTnQVYKwg78GVYMaQc6+Y0zn2I2gS3g4GFAsRc8y2IWyFHN15PQ=
-----END PRIVATE KEY-----
`
export const wxuuid = function () {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 8; i++) { 
	  s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	// s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	// s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	// s[8] = s[13] = s[18] = s[23] = "-";
	// var uuid = s.join("").replace("-","");
	var uuid = s.join("");
	return uuid
  }